package tc.orcl.lab5;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Sax extends DefaultHandler
{
	
	public String xmlFileName = "";
	
	private String thisElement = "",
				   thisValue   = "";
	
	public String login    = "",
				  password = "",
				  ip       = "",
				  dbname   = "";
	
	public Sax(String xmlFileName)
	{
		this.xmlFileName = xmlFileName;
	}
	
	public void parseDocument()
	{
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = null;
		try
		{
			parser = factory.newSAXParser();
			parser.parse(new File(xmlFileName), this);
		}
		catch (ParserConfigurationException e)
		{
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		catch (SAXException e)
		{
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		catch (IOException e)
		{
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
	
	public void printData()
	{
		System.out.printf("%s/%s at %s:%s\n", login, password, ip, dbname);
	}
	
	@Override
	public void startDocument() throws SAXException
	{
		System.out.println("Start parse XML...");
	}
	
	@Override
	public void endDocument() throws SAXException
	{
		System.out.println("Stop parse XML...");
	}
	
	@Override
	public void startElement (String uri, String localName,
            				  String qName, Attributes attributes)
    throws SAXException
	{
		thisElement = qName;
//		System.out.printf("Start element = %s\n", qName);
//		if (attributes != null)
//		{
//			int length = attributes.getLength();
//			for (int i = 0; i < length; i++)
//			{
//				System.out.printf("Attribute = %s\n", attributes.getLocalName(i));
//				System.out.printf("Attribute value = %s\n", attributes.getValue(i));
//			}
//		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
	throws SAXException
	{
		switch (thisElement.toLowerCase())
		{
			case "login": login = thisValue;
			case "password": password = thisValue;
			case "ip": ip = thisValue;
			case "dbname": dbname = thisValue;
		}
		thisElement = "";
		thisValue = "";
//		System.out.printf("End element = %s\n", qName);
	}
	
	@Override
	public void characters(char ch[], int start, int length)
	throws SAXException
	{
		thisValue = new String(ch, start, length);
//		System.out.printf("Value = %s\n", thisValue);
	}
	
	
	
	
	
}
